package util

import java.util.regex.Pattern

import org.apache.commons.codec.digest.DigestUtils

class Utils {

	static Pattern patId = ~/\d+/
	static Pattern patOpenid = ~/([a-z]|[A-Z]|\_|\-|\d){10,50}/

	static boolean isIdValid(String str){
		str ==~ patId
	}

	static boolean isOpenidValid(String str){
		str ==~ patOpenid
	}

	static String encode(String str){
		DigestUtils.shaHex(str)
	}

	static String uuid(){
		'' + System.currentTimeMillis() + '_' + new Random().nextInt(10000)
	}

	static Map getMapInKeys(Object obj, String keys){
		Map r = [:]

		for(key in keys.split(','))
			r[key] = obj.get(key)

		r
	}

	static String generateQueryString(Map params, String keys){
		def sb = new StringBuffer()

		for(key in keys.split(',')){
			sb << key
			sb << '='
			sb << URLEncoder.encode('' + params[key])
			sb << '&'
		}

		sb.toString()
	}
}